<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <a-row>
        <a-col :span="6">
          <div class="instructions-left">
            <div class="ins-search flex">
              <span>搜索</span>
              <a-input ref="userNameInput" v-model="keyword" placeholder="请输入" @keydown.enter="getEventByUserId(false)">
                <a-icon class="instructions--search" slot="suffix" type="search" @click.stop="getEventByUserId(false)" />
              </a-input>
            </div>
            <div class="ins-event" v-if="list.length">
                <div :class="['ins-event-each', active == item.eventId ? 'active' : '']" @click="select(item, i)"
                  v-for="(item, i) in list" :key="`${item.id}-${i}`">
                  <a-badge style="width: 75%" :count="item.noReplyNum">
                    <div>
                      <h1 class="ellipsis">{{ item.title | htmlFilter }}</h1>
                    </div>
                  </a-badge>
                  <p class="ellipsis-2">{{ item.createTime }}</p>
                  <div class="ins-time">{{ item.lastTime }}</div>
                </div>

            </div>
            <a-empty v-else style="margin-top: 30px"></a-empty>
          </div>
        </a-col>
        <a-col :span="18">
          <div class="chat-cnt">
            <div :class="['chat-each', `chat-each-${item.type}`]" v-for="item in chatList" :key="item.key">
              <div :class="['chat-header']">
                <h1>{{ item.type == 0 ? '事件：' : ''}}{{item.title | htmlFilter}}</h1>
                <span>{{item.lastTime}}</span>
              </div>
              <div class="chat-msg" v-if="item.content">
                {{ item.type == 0 ? '指令：' : '我的回复：'}}{{item.content | htmlFilter}}
                <div class="upload-list" v-if="item.enclosure">
                  <div class="upload-each" v-for="item in fileFormat(item.enclosure)" :key="item.url">
                    <svg-icon v-if="['pdf'].includes(item.type.toLowerCase())" iconClass="pdf" />
                    <svg-icon v-else-if="['doc', 'docx'].includes(item.type.toLowerCase())" iconClass="word" />
                    <svg-icon v-else-if="['png', 'jpg', 'jpeg', 'gif'].includes(item.type.toLowerCase())"
                      iconClass="image" />
                    <svg-icon v-else iconClass="file" />
                    <span class="ellipsis">
                      {{item.url}}
                    </span>
                  </div>
                </div>
              </div>
              <div class="chat-action" v-if="item.type == 1 && formArr.length && !item.content">
                <a-textarea :rows="3" v-model="formArr[item.index].replyContent" class="reply-textarea"></a-textarea>
                <div class="upload-list" v-if="formArr[item.index].uploadList.length">
                  <div class="upload-each" v-for="item in formArr[item.index].uploadList" :key="item.url">
                    <svg-icon v-if="['pdf'].includes(item.fileType.toLowerCase())" iconClass="pdf" />
                    <svg-icon v-else-if="['doc', 'docx'].includes(item.fileType.toLowerCase())" iconClass="word" />
                    <svg-icon v-else-if="['png', 'jpg', 'jpeg', 'gif'].includes(item.fileType.toLowerCase())"
                      iconClass="image" />
                    <svg-icon v-else iconClass="file" />
                    <span class="ellipsis">
                      {{item.name}}
                    </span>
                  </div>
                </div>
                <div class="btn-action">
                  <a-space>
                    <!-- <a-button type="primary">上传附件</a-button> -->
                    <UploadImageMutil type="button" :showUploadList="false" @change="getUrl($event, item.index)" :length="20" />
                    <a-button type="primary" @click="addReplyContent(formArr[item.index])">发送</a-button>
                  </a-space>
                </div>
              </div>
            </div>
          </div>

        </a-col>
      </a-row>
    </a-card>
  </page-header-wrapper>
</template>
<script>
import { getEventByUserId, getAskContent, addReplyContent } from '@/api/api'
import UploadImageMutil from '@/components/UploadImageMutil'
import { mapState } from 'vuex'
// import { cloneDeep } from 'lodash'

// const a = [
//   {
//     'askContent': '提问1',
//     'replyContent': '',
//     createTime: '2022-08-27 08:00',
//     id: 1
//   },
//   {
//     'askContent': '提问2',
//     'replyContent': null,
//     createTime: '2022-08-27 10:00',
//     id: 2
//   },
//   {
//     'askContent': '提问3',
//     'replyContent': null,
//     createTime: '2022-08-27 12:00',
//     id: 3
//   }
// ]
// const b = [
//   {
//     'askContent': '',
//     'replyContent': '回复1',
//     createTime: '2022-08-27 10:00',
//     id: 4
//   },
//   {
//     'askContent': '',
//     'replyContent': '回复2',
//     createTime: '2022-08-27 11:00',
//     id: 5
//   },
//   {
//     'askContent': '',
//     'replyContent': '回复3',
//     createTime: '2022-08-27 13:00',
//     id: 6
//   }
// ]

let Inter = ''
export default {
  components: {
    UploadImageMutil
  },
  data () {
    return {
      keyword: '',
      list: [],
      chatList: [],
      active: -1,
      uploadList: [],
      formArr: [],
      form: {
        replyContent: '',
        id: '',
        enclosure: ''
      }
    }
  },
  created () {
    this.getEventByUserId()
    Inter = setInterval(() => {
      this.getEventByUserId(true)
    }, 10000)
  },
  beforeDestroy () {
    Inter && clearInterval(Inter)
  },
  computed: {
    ...mapState({
      info: state => state.user.info
    }),
    fileFormat () {
      return function (file) {
        if (!file) return []
        const list = file.split(',')
        return list.map(e => {
          const index = e.lastIndexOf('.')
          return {
            type: e.substring(index + 1, e.length).toLowerCase(),
            url: e
          }
        })
      }
    }
  },
  methods: {
    getEventByUserId (notSelect) {
      getEventByUserId({
        title: this.keyword
      }).then(res => {
        if (res.length) {
          const eventIdIndex = {}
          let eventId = res.map(e => {
            return e.eventId
          })
          eventId = Array.from(new Set(eventId))
          this.list = res.map(e => {
            if (eventId.includes(e.eventId)) {
              eventIdIndex[e.eventId] = eventIdIndex[e.eventId] ? eventIdIndex[e.eventId] + 1 : 1
              e.sort = eventIdIndex[e.eventId]
            }
            return e
          })

          if (!notSelect) this.select(this.list[0], 0, this.list[0].sort)
        } else {
          this.form = {
            replyContent: '',
            id: '',
            enclosure: ''
          }
          this.chatList = []
        }
      })
    },
    select ({ eventId, id, title, sort }, i) {
      this.chatList = []
      this.active = eventId
      this.form.eventId = eventId
      this.form.title = title
      this.form.sort = sort
      this.getContent(eventId, title, sort)
    },
    getContent (eventId, title) {
      this.formArr = []
      getAskContent({ eventId }).then(res => {
        console.log(res, 'reee')
        const chatList = res && res.map((e, i) => {
          this.formArr.push({
            replyContent: '',
            id: e.id,
            enclosure: '',
            uploadList: []
          })
          return [
            {
              title,
              content: e.askContent,
              lastTime: e.createTime,
              type: 0,
              id: e.id,
              key: `${e.id}-${i}`,
              i

            },
            {
              lastTime: e.replyTime,
              content: e.replyContent,
              title: e.depart,
              type: 1,
              id: e.id,
              i: i + 0.1,
              key: `${e.id}-${i + 0.1}`,
              index: i
            }
          ]
        })
        this.chatList = chatList.reduce((acc, cur) => {
          return acc.concat(cur)
        }, [])
        console.log(this.chatList, 'this.chatList')
      })

      // let res = await Promise.all([getAskContent({ eventId }), getReplyContent({ eventId })])
      // // if (process.env.NODE_ENV == 'development') {
      // //   res = [a, b]
      // // }
      // res[0] = res[0].map(e => {
      //   return {
      //     ...e,
      //     title,
      //     content: e.askContent,
      //     type: 0,
      //     lastTime: e.createTime
      //   }
      // })
      // this.form.id = res[0][res[0].length - 1].id
      // res[1] = res[1].map(e => {
      //   console.log(e)
      //   return {
      //     ...e,
      //     title: '我',
      //     content: e.replyContent,
      //     type: 1,
      //     lastTime: e.replyTime
      //   }
      // })
      // const data = res.reduce((acc, cur) => {
      //   return acc.concat(cur)
      // }, [])

      // data.sort((a, b) => {
      //   return a.lastTime.localeCompare(b.lastTime) || b.type - a.type
      // })

      // this.chatList = data
      // console.log(this.chatList, 'resres')
    },
    // async getContent (eventId, title, sort) {
    //   let res = await Promise.all([getAskContent({ eventId }), getReplyContent({ eventId })])
    //   const result = []
    //   let ask = res[0]
    //   let reply = res[1]

    //   result[0] = (ask.length && ask.map(e => {
    //     if (e) {
    //       return {
    //         ...e,
    //         title,
    //         content: e.askContent,
    //         type: 0
    //       }
    //     } else {
    //       return {}
    //     }
    //   })[sort - 1])
    //   result[1] = (reply.length && reply.map(e => {
    //     if (e) {
    //       return {
    //         ...e,
    //         title: '我',
    //         content: e.replyContent,
    //         type: 1
    //       }
    //     } else {
    //       return {}
    //     }
    //   })[sort - 1])

    //   this.chatList = result.filter(e => e.title)
    //   console.log(result, 'resres')
    // },
    getReplyContent (eventId) {

    },
    getUrl (file, i) {
      console.log(file)
      this.formArr[i].uploadList = file.map(e => {
        return {
          ...e,
          fileType: (e.imgUrl && e.imgUrl.substring(e.imgUrl.lastIndexOf('.') + 1, e.imgUrl.length)) || ''
        }
      })
      console.log(this.uploadList)
      this.formArr[i].enclosure = this.formArr[i].uploadList.map(e => e.imgUrl).join(',')
    },
    addReplyContent (form) {
      if (!form.replyContent) {
        this.$message.error('请输入回复内容！')
        return
      }
      addReplyContent(form).then(res => {
        delete form.uploadList
        console.log(form, 'foooo')
        this.getContent(this.form.eventId, this.form.title)
        this.$message.success('回复成功')
        // this.uploadList = []
      })
    }
  }
}
</script>
<style lang="less" scoped>
h1,p {
  margin: 0;
}
.flex {
  display: flex;
  align-items: center;
  >span:first-child {
    flex-basis: 60px;
  }
}
.ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.ellipsis-2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.instructions-left {
  border-right: 1px solid #efefef;
  padding-right: 20px;
}
.ins-event {
  height: 600px;
  overflow-y: scroll;
  width: calc(100% + 26px);
  &::-webkit-scrollbar {
    width: 6px;
    height: 1px;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: transparent;
  }

  &::-webkit-scrollbar-track {
    // border-radius: 10px;
    // background: #EDEDED;
  }
}
.ins-search {
  padding: 20px 0;
  border-bottom: 1px solid #ddd;
}
.instructions--search {
  cursor: pointer;
}
.ins-event {
  .ins-event-each {
    padding: 10px 24px;
    padding-right: 0;
    box-sizing: border-box;
    margin-top: 8px;
    position: relative;
    cursor: pointer;
    &:hover,&.active {
      background: #F4F9FD;
    }
    &.active {
      &::after {
        content: ' ';
        position: absolute;
        right: 0;
        height: 100%;
        width: 4px;
        background: #3F8CFF;
        border-radius: 2px;
        top: 0;
      }
    }
    h1 {
      font-size: 16px;
      color: #0A1629;
      line-height: 24px;
      margin-bottom: 6px;
      width: 87%;
    }
    p {
      font-size: 14px;
      color: #91929E;
    }
  }
  .ins-time {
    font-size: 14px;
    color: #7D8592;
    position: absolute;
    right: 28px;
    top: 10px;
  }
}
.chat-cnt {
  height: 480px;
  // background: #ddd;
  margin: 0 20px;
  margin-top: 73px;
  overflow-y: auto;
  padding: 0 20px;
  &::-webkit-scrollbar {
    width: 6px;
    height: 1px;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: #ddd;
  }

  &::-webkit-scrollbar-track {
    border-radius: 10px;
    background: #EDEDED;
  }
  .chat-each{
    margin-bottom: 40px;
    .chat-header {
      display: flex;
      >h1 {
        max-width: 80%;
        font-size: 16px;
        color: #0A1629;
        line-height: 24px;
      }
      span {
        font-size: 14px;
        color: #7D8592;
        line-height: 24px;
        margin-left: 14px;
      }
    }
    .chat-msg {
      margin-top: 12px;
      font-size: 16px;
      color: #999;
      line-height: 24px;
    }

    &.chat-each-1 {
      .chat-header {
        justify-content: flex-end;
        >h1 {
          max-width: 100%;
        }
      }
      .chat-msg {
        color: #fff;
        background: #3F8CFF;
        padding: 16px 28px;
        border-radius: 15px;
      }
    }
  }

}
.chat-action {
  box-shadow: 0px 1px 2px 1px rgba(184, 200, 224, 0.22);
  border-radius: 14px 14px 14px 14px;
  border: 1px solid #D8E0F0;
  min-height: 120px;
  margin: 0 20px;
  margin-top: 20px;
  overflow: hidden;
  position: relative;
  .btn-action {
    position: absolute;
    right: 8px;
    bottom: 12px;
    button {
      border-radius: 8px;
    }
  }
}
.reply-textarea {
  border: none;
  resize: none;
  padding: 12px 16px;
  &:focus {
    border: none;
    outline: none;
    box-shadow: none;
  }
}
.upload-list {
  width: 70%;
  display: flex;
}
.upload-each {
  width: 190px;
  height: 45px;
  margin: 4px;
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 0 12px;
  .svg-icon {
    font-size: 30px;
    flex-basis: 30px;
    flex-shrink: 0;
  }
  >span {
    margin-left: 8px;
  }
}
.chat-msg {
  .upload-list {
    margin-top: 8px;
  }
  .upload-each {
    background: #fff;
    color: #333;
  }
}
.ant-badge-count{
  top:100px
}
</style>
